#include <QInputDialog>
#include <QGraphicsDropShadowEffect>
#include <QDebug>
#include <QLabel>
#include "studypage.h"
#include "ui_studypage.h"
#include "util/messagebox.h"

namespace WordMemory
{

    const int StudyPage::LOCAL_VOCAB_ID = 99;

    StudyPage::StudyPage(QWidget *parent)
        : QWidget(parent)
        , ui(new Ui::StudyPage)
        , serverhelper(new ServerHelper(this))
        , localVocabPlaceholder(LOCAL_VOCAB_ID, UserManager::instance().isLoggedIn() ? UserManager::instance().getUserId() : 0, "我的下载")
    {
        ui->setupUi(this);
        setupStyles();
        setupConnections();

        refreshOnlineVocabularies();
        refreshLocalWordsDisplay();
    }

    StudyPage::~StudyPage()
    {
        delete ui;
    }

    void StudyPage::setupStyles()
    {
        // 搜索框样式
        QString searchEditStyle = R"(
            QLineEdit {
              font-family: "Microsoft YaHei";
              font-size: 15px;
              padding: 8px;
              border: 1px solid #d9d9d9;
              border-radius: 5px;
            }
            QLineEdit:hover {
              border: 1px solid #40a9ff;
            }
            QLineEdit:focus {
              border: 1px solid #1890ff;
            })";
        ui->wordSearchEdit->setStyleSheet(searchEditStyle);

        // 按钮样式
        QString buttonStyle = R"(
            QPushButton {
              font-family: "Microsoft YaHei";
              font-size: 15px;
              padding: 8px;
              background-color: #1890ff;
              color: #ffffff;
              border-radius: 5px;
              border: none;
            }
            QPushButton:hover {
              background-color: #40a9ff;
            }
            QPushButton:pressed {
              background-color: #096dd9;
            })";
        ui->searchButton->setStyleSheet(buttonStyle);
        ui->addVocabularyButton->setStyleSheet(buttonStyle);

        // 词库列表样式
        QString listStyle = R"(
            QListWidget {
              font-family: "Microsoft YaHei";
              font-size: 15px;
              border: 1px solid #d9d9d9;
              border-radius: 5px;
              padding: 5px;
              min-height: 400px;
            }
            QListWidget::item {
              padding: 8px;
              height: 50px;
            }
            QListWidget::item:hover {
              background-color: #f5f5f5;
            }
            QListWidget::item:selected {
              background-color: #1890ff;
              color: #ffffff;
            })";
        ui->vocabulariesListWidget->setStyleSheet(listStyle);
        ui->vocabulariesListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

        // 为卡片容器添加阴影效果
        QGraphicsDropShadowEffect *searchShadow = new QGraphicsDropShadowEffect(this);
        searchShadow->setBlurRadius(12);
        searchShadow->setXOffset(0);
        searchShadow->setYOffset(4);
        searchShadow->setColor(QColor(0, 0, 0, 0.1 * 255));
        ui->searchCardWidget->setGraphicsEffect(searchShadow);

        QGraphicsDropShadowEffect *vocabShadow = new QGraphicsDropShadowEffect(this);
        vocabShadow->setBlurRadius(12);
        vocabShadow->setXOffset(0);
        vocabShadow->setYOffset(4);
        vocabShadow->setColor(QColor(0, 0, 0, 0.1 * 255));
        ui->vocabulariesCardWidget->setGraphicsEffect(vocabShadow);
    }

    void StudyPage::setupConnections()
    {
        connect(serverhelper, &ServerHelper::addVocabularyFinished, this,
                [this](bool success, const Vocabulary &vocabulary, const QString &error) {
                    if (success) {
                        (Vocabulary)vocabulary;
                        refreshOnlineVocabularies();
                        MessageBox::info(this, "添加词库成功");
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "添加词库失败" : error);
                    }
                });

        connect(serverhelper, &ServerHelper::getVocabulariesFinished, this,
                [this](bool success, const QList<Vocabulary> &vocabularies, const QString &error) {
                    if (success) {
                        onlineVocabulariesList = vocabularies;
                        updateVocabulariesDisplayList();
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "获取词库失败" : error);
                    }
                });

        connect(serverhelper, &ServerHelper::getDefaultVocabularyFinished, this,
                [this](bool success, const Vocabulary &vocabulary, const QString &error) {
                    if (success) {
                        defaultVocabulary = vocabulary;
                        updateVocabulariesDisplayList();
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "获取默认词库失败" : error);
                    }
                });

        connect(serverhelper, &ServerHelper::setDefaultVocabularyFinished, this,
                [this](bool success, const QString &error) {
                    if (success) {
                        refreshOnlineVocabularies();
                        MessageBox::info(this, "设置默认词库成功");
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "设置默认词库失败" : error);
                    }
                });

        connect(&LocalWordManager::instance(), &LocalWordManager::downloadedWordsChanged, this, &StudyPage::refreshLocalWordsDisplay);
    }

    void StudyPage::refreshOnlineVocabularies()
    {
        if (!UserManager::instance().isLoggedIn())
            return;

        int userId = UserManager::instance().getUserId();
        serverhelper->getVocabularies(userId);
        serverhelper->getDefaultVocabulary(userId);
    }

    void StudyPage::refreshLocalWordsDisplay()
    {
        if (UserManager::instance().isLoggedIn()) {
            localVocabPlaceholder.wordCount =  LocalWordManager::instance().loadDownloadedWords().count();
        } else {
            localVocabPlaceholder.wordCount = 0;
        }
        updateVocabulariesDisplayList();
    }

    void StudyPage::updateVocabulariesDisplayList()
    {
        ui->vocabulariesListWidget->clear();
        for (const Vocabulary &vocab : onlineVocabulariesList) {
            QWidget *itemWidget = new QWidget;
            QHBoxLayout *layout = new QHBoxLayout(itemWidget);
            layout->setContentsMargins(5, 5, 5, 5);
            layout->setSpacing(10);

            QPushButton *defaultButton = new QPushButton("使用");
            defaultButton->setStyleSheet(R"(
                QPushButton {
                  font-family: "Microsoft YaHei";
                  font-size: 12px;
                  padding: 5px;
                  background-color: #1890ff;
                  color: #ffffff;
                  border-radius: 5px;
                  border: none;
                }
                QPushButton:hover {
                  background-color: #40a9ff;
                }
                QPushButton:pressed {
                  background-color: #096dd9;
                }
                QPushButton:disabled {
                  background-color: #d9d9d9;
                  color: #ffffff;
                })");
            defaultButton->setFixedSize(40, 24);
            defaultButton->setEnabled(!vocab.isDefault);
            connect(defaultButton, &QPushButton::clicked, this, [this, vocab]() {
                onSetDefaultVocabularyButtonClicked(vocab.id);
            });

            QLabel *label = new QLabel(vocab.name);
            label->setStyleSheet("font-family: 'Microsoft YaHei'; font-size: 14px;");
            layout->addWidget(defaultButton);
            layout->addWidget(label);

            if (vocab.isFavorites) {
                 QLabel *favoritesTagLabel = new QLabel("我的收藏");
                 favoritesTagLabel->setStyleSheet(
                     "QLabel {"
                     "  font-family: 'Microsoft YaHei';"
                     "  font-size: 12px;"
                     "  color: #8C5400;"
                     "  background-color: #FFFBE6;"
                     "  border: 1px solid #FFE58F;"
                     "  border-radius: 3px;"
                     "  padding: 1px 4px 1px 4px;"
                     "  margin: 5px 0px 5px 5px;"
                     "}");
                 layout->addWidget(favoritesTagLabel);
            }
            if (vocab.isMistakesBook) {
                QLabel *tagLabel = new QLabel("错题本");
                tagLabel->setStyleSheet(
                    "QLabel { "
                    "  font-family: 'Microsoft YaHei'; "
                    "  font-size: 12px; "
                    "  color: #A61D24;"
                    "  background-color: #FFF1F0; "
                    "  border: 1px solid #FFCCC7;"
                    "  border-radius: 3px; "
                    "  padding: 1px 4px 1px 4px;"
                    "  margin: 5px 0px 5px 5px; "
                    "}");
                layout->addWidget(tagLabel);
            }

            layout->addStretch(1);

            QLabel *countLabel = new QLabel(QString::number(vocab.wordCount) + "词");
            countLabel->setStyleSheet("font-family: 'Microsoft YaHei'; font-size: 11px; color: #8c8c8c; margin-left: 5px;");
            layout->addWidget(countLabel);

            itemWidget->setLayout(layout);

            QListWidgetItem *item = new QListWidgetItem;
            ui->vocabulariesListWidget->addItem(item);
            ui->vocabulariesListWidget->setItemWidget(item, itemWidget);
        }

        // 添加本地下载词库
        QWidget *localItemWidget = new QWidget;
        QHBoxLayout *localLayout = new QHBoxLayout(localItemWidget);
        localLayout->setContentsMargins(5, 5, 5, 5); localLayout->setSpacing(10);

        QLabel *localNameLabel = new QLabel(localVocabPlaceholder.name);
        localNameLabel->setStyleSheet("font-family: 'Microsoft YaHei'; font-size: 15px; font-weight:bold; background-color:transparent; color: #0050b3;");

        localLayout->addWidget(localNameLabel);
        localLayout->addStretch(1);
        QLabel *localCountLabel = new QLabel(QString::number(localVocabPlaceholder.wordCount) + "词");
        localCountLabel->setStyleSheet("font-family: 'Microsoft YaHei'; font-size: 11px; color: #8c8c8c; margin-left: 5px; background-color:transparent;");
        localLayout->addWidget(localCountLabel);
        localItemWidget->setLayout(localLayout);

        QListWidgetItem *localItem = new QListWidgetItem;
        localItem->setData(Qt::UserRole, localVocabPlaceholder.id);
        ui->vocabulariesListWidget->addItem(localItem);
        ui->vocabulariesListWidget->setItemWidget(localItem, localItemWidget);
    }

    void StudyPage::on_searchButton_clicked()
    {
        QString word = ui->wordSearchEdit->text().trimmed();
        if (word.isEmpty()) {
            MessageBox::warning(this, "请输入单词");
            return;
        }
        emit searchWordAndSwitchPage(word);
    }

    void StudyPage::on_addVocabularyButton_clicked()
    {
        if (!UserManager::instance().isLoggedIn()) {
            MessageBox::warning(this, "请先登录");
            return;
        }

        bool ok;
        QString vocabName = QInputDialog::getText(this, "添加词库", "请输入词库名称：", QLineEdit::Normal, "", &ok);
        if (ok && !vocabName.isEmpty()) {
            int userId = UserManager::instance().getUserId();
            serverhelper->addVocabulary(userId, vocabName);
        }
    }

    void StudyPage::on_vocabulariesListWidget_itemClicked(QListWidgetItem *item)
    {
        if (!UserManager::instance().isLoggedIn()) {
            MessageBox::warning(this, "请先登录");
            return;
        }

        int index = ui->vocabulariesListWidget->row(item);
        if (index >= 0 && index < onlineVocabulariesList.size()) {
            emit showVocabularyWordsPage(onlineVocabulariesList[index]);
        }
    }

    void StudyPage::onSetDefaultVocabularyButtonClicked(int vocabId)
    {
        if (!UserManager::instance().isLoggedIn()) {
            MessageBox::warning(this, "请先登录");
            return;
        }

        int userId = UserManager::instance().getUserId();
        serverhelper->setDefaultVocabulary(userId, vocabId);
    }

    void StudyPage::onDictatingDoneRefreshVocabList() {
        refreshOnlineVocabularies();
    }
}
